package wei.qiang.ye.springbootdatasource.config;

import com.zaxxer.hikari.HikariDataSource;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.util.StringUtils;

import javax.sql.DataSource;

/**
 * HikariCP 多数据源配置类
 */
@Configuration
public class DataSourceConfig {

    /**
     * 创建 liugh 数据源的配置对象
     * @Primary 注解，保证项目中有一个主的 DataSourceProperties Bean
     * @Bean(name = "liughDataSourceProperties") 注解，会创建一个名字为 "liughDataSourceProperties" 的 DataSourceProperties Bean
     * @ConfigurationProperties(prefix = "spring.datasource.liugh") 注解，会将 "spring.datasource.liugh" 配置项，逐个属性赋值给DataSourceProperties Bean
     */
    @Primary
    @Bean(name = "liughDataSourceProperties")
    @ConfigurationProperties(prefix = "spring.datasource.liugh") // 读取 spring.datasource.liugh 配置到 DataSourceProperties 对象
    public DataSourceProperties liughDataSourceProperties() {
        return new DataSourceProperties();
    }

    /**
     * 创建 liugh 数据源
     */
    @Bean(name = "liughDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.liugh.hikari") // 读取 spring.datasource.liugh 配置到 HikariDataSource 对象
    public DataSource liughDataSource() {
        //获得 DataSourceProperties 对象
        DataSourceProperties properties =  this.liughDataSourceProperties();
        //创建 HikariDataSource 对象
        return createHikariDataSource(properties);
    }

    /**
     * 创建 users 数据源的配置对象
     */
    @Bean(name = "usersDataSourceProperties")
    @ConfigurationProperties(prefix = "spring.datasource.users") // 读取 spring.datasource.users 配置到 DataSourceProperties 对象
    public DataSourceProperties usersDataSourceProperties() {
        return new DataSourceProperties();
    }

    /**
     * 创建 users 数据源
     */
    @Bean(name = "usersDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.users.hikari")
    public DataSource usersDataSource() {
        // 获得 DataSourceProperties 对象
        DataSourceProperties properties =  this.usersDataSourceProperties();
        // 创建 HikariDataSource 对象
        return createHikariDataSource(properties);
    }

    private static HikariDataSource createHikariDataSource(DataSourceProperties properties) {
        // 创建 HikariDataSource 对象
        HikariDataSource dataSource = properties.initializeDataSourceBuilder().type(HikariDataSource.class).build();
        // 设置线程池名
        if (StringUtils.hasText(properties.getName())) {
            dataSource.setPoolName(properties.getName());
        }
        return dataSource;
    }

}
